package com.bw.controller;

import com.bw.entity.*;
import com.bw.mapper.StudentMapper;
import com.bw.service.StudentService;
import org.spring.kun.common.TokenUtils;
import org.spring.kun.common.ZzyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    StudentService studentService;



    @RequestMapping("/list.do")
    public String list(StudentQuery query, Model model, HttpServletRequest request){
        User userFromRequest = TokenUtils.getLoginUserFromRequest(request, User.class);

        model.addAttribute("nickName",userFromRequest.getNickName());
        model.addAttribute("avatarUrl",userFromRequest.getAvatarUrl());


        // 直接查询
       List<StudentRoom> list =  studentMapper.selectByParam(query);
       model.addAttribute("list",list);
        return "list";
    }


    @RequestMapping("/addPage.do")
    public String addPage(Model model){

        // 3下拉框
        List<Dict> studentList =  studentMapper.studentList();
        model.addAttribute("studentList",studentList);

        List<Dict> roomList =  studentMapper.roomList();
        model.addAttribute("roomList",roomList);

        List<Dict> apartmentList =  studentMapper.apartmentList();
        model.addAttribute("apartmentList",apartmentList);
        return "add";
    }
    @RequestMapping("/add.do")
    public String add(@Valid StudentRoomAdd studentRoomAdd, BindingResult result,Model model){

        if (result.hasErrors()){
            model.addAttribute("error",result.getAllErrors().get(0).getDefaultMessage());
            // 3下拉框
            List<Dict> studentList =  studentMapper.studentList();
            model.addAttribute("studentList",studentList);

            List<Dict> roomList =  studentMapper.roomList();
            model.addAttribute("roomList",roomList);

            List<Dict> apartmentList =  studentMapper.apartmentList();
            model.addAttribute("apartmentList",apartmentList);
            return "add";
        }
        studentService.add(studentRoomAdd);
        ZzyUtils.sendSms("17343092621","入住成功",5);
        return "redirect:list.do";
    }
}
